package qplayas

import com.gargoylesoftware.htmlunit.BrowserVersion;

class PlayaGeoJob {

	static triggers = {
		simple name: 'playaGeoJob', startDelay: 600000, repeatInterval: 604800000l
	}
	
	def playaGeoJobService
	
    def execute() {	
		def noPlayas = Playa.count()
		if (noPlayas > 500){
		def builder =
		new qplayas.crawling.builder.HtmlUnitBuilder().
			client(BrowserVersion.FIREFOX_3_6) {
				page(url:'http://www.dices.net/playas/') {
				  def cp = currentPage
				  elementsByXPath("//table[@width='900']/tbody/tr[4]/td[1]/a").each{a->
					  def provincia = a.hrefAttribute
					  def nombreProvincia = provincia.replace('playas.php?provincia=','')
					  def urlProvincia = cp.getFullyQualifiedUrl(provincia).toString()					 
					  page(url:urlProvincia){
						  elementsByXPath("//table[@width='900']/tbody/tr[4]/child::*/ul/a").each{a2->
							  def municipio = a2.hrefAttribute
							  def nombreMunicipio = municipio.replace('http://www.dices.net/playas/playas-municipio.php?municipio=','')
							  page(url:municipio){
								   elementsByXPath("//table[@width='900']/tbody/tr[4]/child::*/ul/a").each{a3->
									   def playaUrl = a3.hrefAttribute
									   page(url:playaUrl){										   
										   
										   def elementos = elementsByXPath("//h1")[0].textContent.split(',')
										   def name = elementos[0].trim().replaceAll('Playa del','').replaceAll('Playa de','')
										   
										   def lat = elementsByXPath("//td[@class='fondoblanco']/p/b[5]")[0].textContent.trim()
										   def lon = elementsByXPath("//td[@class='fondoblanco']/p/b[6]")[0].textContent.trim()
										   
										   /* ------------------------------------------------------------------------------------------------------------------- */
										   /* -------------------------------------------------- NORMALIZACION DE NOMBRES --------------------------------------- */
										   /* ------------------------------------------------------------------------------------------------------------------- */
											 def beachNameNormalized = normalizeName(nombreProvincia.toLowerCase()+name)
										   /* ------------------------------------------------------------------------------------------------------------------- */
										   /* ------------------------------------------------------------------------------------------------------------------- */
										   /* ------------------------------------------------------------------------------------------------------------------- */
											 
										   println "GEO:"+"GEOLOCALIZANDO $beachNameNormalized"
										   
										   playaGeoJobService.geoUpdate(beachNameNormalized,lat,lon)
									   }
								   }
							  }
						  }
					  }
				  }
				}
			}
		}
    }
}
